<?php

class Request
{
	public function __construct ($cfg)
	{
		foreach ($cfg as $k=>$v) $this->$k = $v;
		$this->init();
	} // end of __construct
	public function init ()
	{
		/*
		 * удаляем "магические" квоты из предоставленного массива и всех содержащихся в нём массивов
		 *
		 * gpc - GET, POST, COOKIE
		 */
		$this->_GET = $_GET;
		$this->_POST = $_POST;
		$this->_COOKIE = $_COOKIE;
		$this->_REQUEST = $_REQUEST;

		if (get_magic_quotes_gpc()) {
			self::fuckQuotes($this->_GET);
			self::fuckQuotes($this->_POST);
			self::fuckQuotes($this->_COOKIE);
			self::fuckQuotes($this->_REQUEST);
		}

		if (!isset($_SERVER['JT_HOST']) || !isset($_SERVER['JT_PORT'])) {
			$server = explode(':', $_SERVER['HTTP_HOST'], 2);
			if (count($server) == 2) {
				$server_host = $server[0];
				$server_port = intval($server[1]);
			} else {
				$server_host = $server[0];
				$server_port = 80;
			}
			if (!isset($_SERVER['JT_HOST'])) { $_SERVER['JT_HOST'] = $server_host; }
			if (!isset($_SERVER['JT_PORT'])) { $_SERVER['JT_PORT'] = $server_port; }
		}
		if (!isset($_SERVER['JT_SCHEME'])) {
			$_SERVER['JT_SCHEME']
				= strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/')));
		}
		// вычисляем base_url
		if (!isset($_SERVER['JT_SERVER']) ) {
			$_SERVER['JT_SERVER'] =
				$_SERVER['JT_SCHEME'] . '://' . $_SERVER['JT_HOST'] . ($_SERVER['JT_PORT'] === 80 ? '' : ':'.$_SERVER['JT_PORT']);
		}
		if (!isset($_SERVER['JT_BASE_PATH'])) {
			$_SERVER['JT_BASE_PATH'] = isset($config['remove_script_name']) ? url_dirname($_SERVER['SCRIPT_NAME']) : $_SERVER['SCRIPT_NAME'];
		}
		if (!isset($_SERVER['JT_BASE_URL'])) {
			$_SERVER['JT_BASE_URL'] = $_SERVER['JT_SERVER'] . $_SERVER['JT_BASE_PATH'];
		}

		if (!isset($_SERVER['JT_REST_PATH'])) {
			$sbn = '/'.basename($_SERVER['SCRIPT_NAME']);
			$sbn_len = strlen($sbn);
			if (substr($_SERVER['JT_BASE_PATH'], 0, $sbn_len) === $sbn) {
				$path = substr($_SERVER['JT_BASE_PATH'], $sbn_len);
				$_SERVER['JT_REST_PATH'] = $path ? $path : '/';
			} else {
				$_SERVER['JT_REST_PATH'] = $_SERVER['JT_BASE_PATH'];
			}
		}
	} // end of method init

	public function redirect ($url)
	{
		if ($url[0] === '?') {
			$url = $_SERVER['SCRIPT_NAME'] . $url;
		}
		header('Location: '.$url);
		die();
	} // end of method redirect

	public function getParam ($ns, $name, $default=NULL)
	{
		$D = $this->$ns;
		if (isset($D[$name])) { return $D[$name]; }
		else { return $default; }
	} // end of method getParam
	public function getBasePath ()
	{
		return $_SERVER['JT_BASE_PATH'];
	} // end of method getBasePath
	public function getBaseUrl ()
	{
		return $_SERVER['JT_BASE_URL'];
	} // end of method getBaseUrl

	static public function fuckQuotes (array &$a)
	{
		foreach($a as $k => $v) {
			if(is_array($v)) {
				self::fuckQuotes( $a[$k] );
			}	else {
				$a[$k] = stripslashes($v);
			}
		}
	} // end of method fuckQuotes

	/**
	 * href создать ссылку
	 *
	 * @param mixed $x array(
	 *                    [scheme] => http,
	 *                    [host] => host name,
	 *                    [port] => port number,
	 *                    [user] => user name,
	 *                    [pass] => user password,
	 *                    [path] => user password,
	 *                    [query] => array(),
	 *                    [fragment] => anchor
	 *                  )
	 * @return string URL
	 */
	public function href ($x)
	{
		if (is_array($x)) {
			$scheme = $host = $port = $user = $pass = $path = $fragment = '';
			$query = array();

			if (isset($x['scheme'])) $scheme = $x['scheme'];
			elseif (isset($this->defaultScheme)) $scheme = $this->defaultScheme;

			if (isset($x['host'])) $host = $x['host'];
			elseif (isset($this->defaultHost)) $host = $this->defaultHost;

			if (isset($x['port'])) $port = $x['port'];
			elseif (isset($this->defaultPort)) $port = $this->defaultPort;

			if (isset($x['user'])) $user = $x['user'];
			elseif (isset($this->defaultUser)) $user = $this->defaultUser;

			if (isset($x['pass'])) $pass = $x['pass'];
			elseif (isset($this->defaultPass)) $pass = $this->defaultPass;

			if (isset($x['path'])) $path = $x['path'];
			if (substr($path, 0, 2) == './') $path = $this->getBasePath() . $substr($path, 2);

			if (isset($x['query'])) $query = $x['query'];
			if (is_array($query)) $query = http_build_query($query);

			if (isset($x['fragment'])) $fragment = $x['fragment'];

			if ($port && $scheme && isset(self::$services[$scheme]) && self::$services[$scheme] == $port) $port = NULL;

			$url = ($scheme ? "$scheme://" : '')
				.($host
					? ($user ? $user.($pass ? ":$pass" : '').'@' : '')
						.$host
						.($port ? ":$port" : '')
					: ''
					)
				.($path ? $path : '')
				.($query ? "?$query" : '')
				.($fragment ? "#$fragment" : '');
		} else {
			$url = $x;
		}
		return $url;
	} // end of method href

	static $services = array(
		'ftp' => 21,
		'http' => 80,
	);
}

function request_fuckQuotes( array &$a )
{
	foreach($a as $k => $v) {
		if(is_array($v)) {
			request_fuckQuotes( $a[$k] );
		}	else {
			$a[$k] = stripslashes($v);
		}
	}
}

function request_init($config=array())
{
	/**
	 * удаляем "магические" квоты из предоставленного массива и всех содержащихся в нём массивов
	 *
	 * gpc - GET, POST, COOKIE
	 */
	if (get_magic_quotes_gpc()) {
		request_fuckQuotes($_GET);
		request_fuckQuotes($_POST);
		request_fuckQuotes($_COOKIE);
		request_fuckQuotes($_REQUEST);
	}
	$_GPC_OFF = true;
	if (!isset($_SERVER['JT_HOST']) || !isset($_SERVER['JT_PORT'])) {
		$server = explode(':', $_SERVER['HTTP_HOST'], 2);
		if (count($server) == 2) {
			$server_host = $server[0];
			$server_port = intval($server[1]);
		} else {
			$server_host = $server[0];
			$server_port = 80;
		}
		if (!isset($_SERVER['JT_HOST'])) { $_SERVER['JT_HOST'] = $server_host; }
		if (!isset($_SERVER['JT_PORT'])) { $_SERVER['JT_PORT'] = $server_port; }
	}
	if (!isset($_SERVER['JT_SCHEME'])) {
		$_SERVER['JT_SCHEME']
		= strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/')));
	}
	// вычисляем base_url
	if (!isset($_SERVER['JT_SERVER']) ) {
		$_SERVER['JT_SERVER'] =
		$_SERVER['JT_SCHEME'] . '://' . $_SERVER['JT_HOST'] . ($_SERVER['JT_PORT'] === 80 ? '' : ':'.$_SERVER['JT_PORT']);
	}
	if (!isset($_SERVER['JT_BASE_PATH'])) {
		$_SERVER['JT_BASE_PATH'] = isset($config['remove_script_name']) ? url_dirname($_SERVER['SCRIPT_NAME']) : $_SERVER['SCRIPT_NAME'];
	}
	if (!isset($_SERVER['JT_BASE_URL'])) {
		$_SERVER['JT_BASE_URL'] = $_SERVER['JT_SERVER'] . $_SERVER['JT_BASE_PATH'];
	}

	if (!isset($_SERVER['JT_REST_PATH'])) {
		$sbn = '/'.basename($_SERVER['SCRIPT_NAME']);
		$sbn_len = strlen($sbn);
		if (substr($_SERVER['JT_BASE_PATH'], 0, $sbn_len) === $sbn) {
			$path = substr($_SERVER['JT_BASE_PATH'], $sbn_len);
			$_SERVER['JT_REST_PATH'] = $path ? $path : '/';
		} else {
			$_SERVER['JT_REST_PATH'] = $_SERVER['JT_BASE_PATH'];
		}
	}
}
function request_redirect ($url)
{
	if ($url[0] === '?') {
		$url = $_SERVER['SCRIPT_NAME'] . $url;
	}
	header('Location: '.$url);
	die();
} // end of function request_redirect
function request_get_param($name, $default=NULL)
{
	if (isset($_REQUEST[$name])) { return $_REQUEST[$name]; }
	else { return $default; }
}
function request_get_base_path ()
{
	return $_SERVER['JT_BASE_PATH'];
} // end of function request_get_base_path
function request_get_base_url ()
{
	return $_SERVER['JT_BASE_URL'];
} // end of function request_get_base_url

?>
